using System.Collections.Generic;
using System;
using System.Linq;
using System.Text;
using Cysharp.Threading.Tasks;
using UnityEngine;
namespace Cesium3DTilesSelection
{
    internal class TileContentFactory
    {
        private static Dictionary<string, TileContentLoader> _loadersByMagic = new Dictionary<string, TileContentLoader>();
        private static Dictionary<string, TileContentLoader> _loadersByContentType = new Dictionary<string, TileContentLoader>();


        private static string getMagic(byte[] data)
        {
            if (data.Length >= 4)
            {
                var head = data.Take(4);
                string tag = Encoding.Default.GetString(head.ToArray());
                return tag;
            }
            return "json";
        }
        public static void registerMagic(string magic, TileContentLoader pLoader)
        {
            _loadersByMagic[magic] = pLoader;
        }

        public static void registerContentType(string contentType, TileContentLoader pLoader)
        {
            _loadersByContentType[contentType] = pLoader;
        }

        internal static UniTask<TileContentLoadResult> createContent(TileContentLoadInput input)
        {
            var data = input.pRequest.downloadHandler.data;
            var magic = getMagic(data);
            if (_loadersByMagic.TryGetValue(magic, out TileContentLoader magicLoader))
            {
                return magicLoader.load(input);
            }
            var contentType = input.pRequest.GetResponseHeader("content-type");
            string baseContentType = contentType.Substring(0, contentType.IndexOf(";"));
            if (_loadersByContentType.TryGetValue(baseContentType, out TileContentLoader contentTypeLoader))
            {
                return   contentTypeLoader.load(input);
            }


            //    for (int i = 0; i < data.Length; i++)
            //    {
            //      if(!char.IsWhiteSpace((char)data[i]))
            //      {

            //      } 
            //    }
            return new UniTask<TileContentLoadResult>();
        }

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        public static void registerAllTileContentTypes()
        {
            registerMagic("glTF", new GltfContent());
            registerMagic("b3dm", new Batched3DModelContent());
            registerMagic("cmpt", new CompositeContent());
            registerMagic("json", new ExternalTilesetContent());
            registerContentType(QuantizedMeshContent.CONTENT_TYPE, new QuantizedMeshContent());
        }
    }
}